//
//  FavouriteViewController.m
//  LilyBBS
//
//  Created by 孙 文翔 on 11-11-21.
//  Copyright (c) 2011年 NANJING UNIVERCITY. All rights reserved.
//

#import "FavouriteViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SingleCookie.h"
#import "TFHpple.h"
#import "BoardDetail.h"
#import "Reachability.h"
#import "LogIn.h"


@implementation FavouriteViewController

@synthesize favourites;

- (id)initWithStyle:(UITableViewStyle)style
{
    self.navigationItem.title=@"预定讨论区";
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    
    Reachability *r = [Reachability reachabilityWithHostName:@"www.nju.edu.cn"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            //没有网络连接
            NSLog(@" ");
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络好像连接不上。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        case ReachableViaWWAN:
            //使用3G网络            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络            
            break;
    }
    
    if ([[SingleCookie sharedSingleCookie].savedCookies count]==0) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"回复提示" message:@"尚未登录，请登录后查看。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
        [alert release];
        return;
        //[self dismissModalViewControllerAnimated:YES];
    }
    
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    //NSLog(@"view did unload");
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self getFavourite];
    [self.tableView reloadData];
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //NSLog(@"view did appear");
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.favourites count]-1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    cell.textLabel.text = [self.favourites objectAtIndex:indexPath.row];
    return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    
    BoardDetail *detailViewController = [[BoardDetail alloc] initWithNibName:@"Top10" bundle:nil];
    detailViewController.titlestring = [self.favourites objectAtIndex:indexPath.row];
    // ...
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
    
}

-(void)getFavourite{
    //if not logged in
    if ([[SingleCookie sharedSingleCookie].savedCookies count]==0) {
        return;
    }
    
    //if logged in
    NSString* urlString = [NSString stringWithFormat:@"http://bbs.nju.edu.cn/vd%@/bbsleft",[SingleCookie sharedSingleCookie].randomNumber];
    NSURL* url = [[NSURL alloc] initWithString:urlString];
    [urlString release];
    ASIHTTPRequest* request = [[ASIHTTPRequest alloc] initWithURL:url];
    [request setUseCookiePersistence:NO];
    [request setRequestCookies:[[SingleCookie sharedSingleCookie]savedCookies]];
    [request startSynchronous];
    NSString* response = [request responseString];
    [request release];
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);    
    NSData* siteData = [response dataUsingEncoding:enc];
    
	TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:siteData];
	NSArray *titles = [xpathParser searchWithXPathQuery:@"//tr/td/div[3]/a"];
    NSMutableArray* titlearr = [[NSMutableArray alloc] init];
	for (TFHppleElement *element in titles) {
		NSString *strs = [element content];
        //NSLog(@"%@",strs);
        if (strs==NULL) {
            continue;
        }
		[titlearr addObject:strs];
    }
    self.favourites = titlearr;
    [titlearr release];
    [xpathParser release];
}

#pragma UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            break;
        case 1:
            NSLog(@"logging in...");
            LogIn* login = [[LogIn alloc] initWithNibName:@"LogIn" bundle:nil];
            UINavigationController *addNavCon = [[UINavigationController alloc] initWithRootViewController:login];
            [self presentModalViewController:addNavCon animated:YES];
            [login release];
            break;
            
        default:
            break;
    }
}

@end
